import './style.less'
import { useEffect, useRef, useState } from 'react'
import { Button, Select, Descriptions, Tag, List, message, Space, Table, Radio } from 'antd';
import { useSelector } from 'react-redux'
import qimg from '@/assets/q.png'
import { getColumns } from './helper'
import { PlusOutlined } from '@ant-design/icons';


function Install() {


  const device = useSelector((state) => state.device)

  const [type, setType] = useState('3');
  const onTypeChange = (e) => {
    setType(e.target.value);
  };

  const onUnload = async (record) => {
    const deviceId = device['ro.serialno']['value'];
    const res = await electronAPI.unInstall(deviceId, record.key);
    syncPkgs();
  }
  const onFreeze = async (record, enable = false) => {
    console.log('开始冻结');
    const deviceId = device['ro.serialno']['value'];
    const res = await electronAPI.disableApp(deviceId, record.key, enable);
    syncPkgs();

  }
  const columns = getColumns(onUnload, onFreeze);

  const [installedApp, setInstalledApp] = useState([]);
  const syncPkgs = async () => {
    const deviceId = device['ro.serialno']['value'];
    const res = await electronAPI.getPkgs(deviceId, type);
    setInstalledApp(res.map(it => ({
      key: it.name,
      name: it.name,
      disable: it.disable
    })))
  }
  useEffect(() => {
    syncPkgs()
  }, [type]) //监听类型变化，获取最新列表


  /**
   * 打开上传文件窗口
   */
  const onSelectFile = async () => {
    let [res] = await electronAPI.openFileDialog(['apk']);
    message.info('正在安装：'+res)
    await electronAPI.installApk(device['ro.serialno']['value'], [res])
    message.success('安装完成：'+res)
    syncPkgs()
  }

  return (
    <div className='pkg'>

      {device ? <div>
        <div className='mb-2 flex flex-row-reverse'>
          <Button onClick={onSelectFile} type="primary"><PlusOutlined />从本地安装</Button>
        </div>
        <Radio.Group value={type} onChange={onTypeChange} size="small" buttonStyle="solid">
          <Radio.Button value="3">三方</Radio.Button>
          <Radio.Button value="s">系统</Radio.Button>
        </Radio.Group>
        <Table columns={columns} dataSource={installedApp} rowClassName="custom-table-row" className="custom-table" pagination={false} />
      </div>
        : <div className='need-device mt-28'>
          <span>设备呢？</span>
          <img src={qimg} alt="" />
        </div>}
    </div>
  )
}

export default Install;
